package com.cwf.quality.common.strategy.filter;

import com.cwf.quality.common.enums.DataCheckFilterEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.datacheck.result.ValueLengthCheckResult;
import com.cwf.quality.model.dto.datacheck.rule.CheckRuleInfo;
import com.cwf.quality.model.dto.datacheck.rule.DataCheckRuleInfo;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValueLengthCheckFilter implements IDataCheckFilter {
    /**
     * 字段长度校验
     *
     * @param dataCheckRuleInfo
     * @return
     */
    @Override
    public QualityResultInfo<ValueLengthCheckResult> checkData(DataCheckRuleInfo dataCheckRuleInfo) {
        SqlUtils sqlUtils = dataCheckRuleInfo.getSqlUtils();

        Map<String, List<ValueLengthCheckResult.ColumnIllegalLength>> columnIllegalLengthCountMap = new HashMap<>();

        List<CheckRuleInfo.ColumnLength> columnLengthList = dataCheckRuleInfo.getCheckRuleInfo().getColumnLengthList();
        for (CheckRuleInfo.ColumnLength columnLength : columnLengthList) {
            String columnName = columnLength.getColumnName();
            Integer length = columnLength.getLength();
            String sql = DataCheckFilterEnum.VALUE_LENGTH_CHECK.getSql()
                    .replace("{table}", dataCheckRuleInfo.getTableName())
                    .replace("{column}", columnName)
                    .replace("{lengthValue}", length.toString());

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, -1);

            List<ValueLengthCheckResult.ColumnIllegalLength> columnIllegalLengthList = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                Object columnValue = map.get(columnName);
                Integer illegalLength = (Integer) map.get("illegal_length");
                columnIllegalLengthList.add(new ValueLengthCheckResult.ColumnIllegalLength(columnValue, illegalLength));
            }
            columnIllegalLengthCountMap.put(columnName, columnIllegalLengthList);
        }

        ValueLengthCheckResult valueLengthCheckResult = new ValueLengthCheckResult();
        valueLengthCheckResult.setColumnIllegalLengthMap(columnIllegalLengthCountMap);
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(valueLengthCheckResult)
                .build();
        return qualityResultInfo;
    }
}
